package cn.imvc.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

/**
 * 分页辅助类
 * 
 * @author lijibo
 *
 */
public class PageableUtils {
	/**
	 * 生成 Pageable 对象
	 * 
	 * @param page
	 * @param size
	 * @param sortStr
	 *            格式 col1_orderType1,col2_orderType2,...
	 * @param zeroStart
	 *            初始页码是否为0
	 * @return
	 */
	public static PageRequest bulidPageRequest(Integer page, Integer size, String sortStr, boolean zeroStart) {
		page = page == null ? new Integer(zeroStart ? 0 : 1) : page;
		Sort sort = null;
		if (sortStr != null && !"".equals(sortStr.trim())) {
			String[] sorts = sortStr.split(",");
			List<Order> orders = new ArrayList<Order>();
			for (String order : sorts) {
				String[] orderInfo = order.split("_");
				if (orderInfo != null && orderInfo.length == 2)
					orders.add(new Order(Direction.fromString(order.split("_")[1]), order.split("_")[0]));
			}
			sort = new Sort(orders);
		} else {
			// sort = new Sort(Direction.DESC, "id");
		}
		return new PageRequest(page, size, sort);
	}
}
